import request from '@/common/js/request.js'
import util from '@/common/util.js'
import {
	rez_path
} from "@/common/js/warehouse.js"
const api = {
	getEntRegInfo: '/entInfo/getEntRegInfo',
	getFacInfo: '/entInfo/getEntRegInfo',
	getPlant: "/entInfo/getEqProPlantInfo"

}


function changeStyle(obj) {
	var objData = {}
	obj.forEach(function(curValue, index, arr) {
		objData[index] = curValue;
	});
	return objData
}


// 更换当前查看页面的id

function changeBookid(lx_bookid, bookid) {
	let requestQueue = uni.getStorageSync('requestQueue')


	if (requestQueue != 'undefined' && requestQueue != null && requestQueue.length >
		0) {
		console.log(requestQueue, "更改查看的bookid之前")
		requestQueue.forEach((item, index) => {
			console.log(item.name.api, '区分', item.parameter.bookid)
			if (item.name.api == '/record/getExRecord' && item.parameter.bookid == lx_bookid) {
				item.parameter.bookid = bookid
				console.log(requestQueue, "更改查看的bookid成功")
				uni.setStorageSync('requestQueue', requestQueue)
			}
		})

	}


}



//上传新增问题地点的缓存
function upSite() {
	return new Promise(async (resolve, reject) => {
		let requestSite = uni.getStorageSync('requestSite')
		// 存储离线时调用接口的动作
		console.log(requestSite)
		if (requestSite != 'undefined' && requestSite != null && requestSite.length > 0) {

			for (let i = 0; i < requestSite.length; i++) {
				// 如果这个上传的数据已经被标记过就不上传
				if (requestSite[i].uflag == true) {
					continue;
				}
				let classObj = typeof requestSite[i].data.ID
				console.log(classObj, '该数据是否为之前有网新建的地点，但是未选中的笔记')
				if (classObj === 'number') {
					// 这里是有原来的id地址，但是没有bookid
					var value = uni.getStorageSync('account')

					//获取记录本的id，然后再获取该记录本的bookid
					//获取bookid

					if (value.isckmission == 3201) {
						await common2({
							missionpeoid: value.missionpeoid,
							peoid: value.peoid,
							placeid: requestSite[i].data.ID,
						}, {
							'api': '/record/saveBookPlace'
						}).then(e => {
							console.log(e, 'bookid获取')
							var res5 = JSON.parse(e.data.data)

							// 更改查看数据的api，

							changeBookid(requestSite[i].lx_bookid, res5.bookid)


							// 修改离线接口的id,此处的id是为了离线地点中的记录本中的材料，替换他们的bookid只有这样才能提交离线数据
							let requestFile = uni.getStorageSync(
								'requestFile')
							// // 调用离线时存储的接口
							if (requestFile != 'undefined' &&
								requestFile != null && requestFile
								.length > 0) {

								console.log(requestFile, '更改前')
								console.log(requestSite,
									"requestSite的数据")
								for (let j = 0; j < requestFile.length; j++) {
									if (requestFile[j].bookid == requestSite[i].lx_bookid) {
										console.log(res5.bookid, '找到该bookid')
										requestFile[j].bookid = res5.bookid
										requestSite[i].realBid = res5.bookid

									}

								}
								console.log("更换子数据bookid成功")
								console.log(requestFile, '更改后')
								uni.setStorageSync('requestFile',
									requestFile)




							}
							// 如果仅仅只是新建离线地点也可能不上传文件
							requestSite[i].uflag = true
							uni.setStorageSync('requestSite',
								requestSite)






						})

					} else {
						await common2({
							missionpeoid: value.missionpeoid,
							peoid: value.peoid,
							placeid: id,
						}, {
							'api': '/record/saveCkBookPlace'
						}).then(e => {
							console.log(e, 'bookid获取')
							var res5 = JSON.parse(e.data.data)

							// 更改查看数据的api，

							changeBookid(requestSite[i].lx_bookid, res5.bookid)
							// 修改离线接口的id,此处的id是为了离线地点中的记录本中的材料，替换他们的bookid只有这样才能提交离线数据
							let requestFile = uni.getStorageSync(
								'requestFile')
							// // 调用离线时存储的接口
							if (requestFile != 'undefined' &&
								requestFile != null && requestFile
								.length > 0) {

								console.log(requestFile, '更改前')
								console.log(requestSite,
									"requestSite的数据")
								for (let j = 0; j < requestFile
									.length; j++) {
									if (requestFile[j].bookid ==
										requestSite[i].lx_bookid) {
										console.log(res5.bookid,
											'找到该bookid')
										requestFile[j].bookid = res5
											.bookid
										requestSite[i].realBid = res5.bookid
									}

								}
								console.log("更换子数据bookid成功")
								console.log(requestFile, '更改后')
								uni.setStorageSync('requestFile',
									requestFile)




							}
							requestSite[i].uflag = true
							uni.setStorageSync('requestSite',
								requestSite)






						})




					}




				} else {
					console.log(requestSite[i].data, '原来地址')
					await upload_picture(requestSite[i].data.photourl).then(async res => {
						if (res) {
							// 更换图片地址
							console.log(res, '图片地址')
							requestSite[i].data.photourl = res
							await common2({
								placeInfo: JSON.stringify(requestSite[i].data)
							}, {
								'api': '/record/savePlaceInfo'
							}).then(async e => {
								console.log(e, '缓存数据')
								console.log(e.data.data, '缓存成功')

								if (e.data.code != 0) {
									uni.showToast({
										title: '缓存提交新增地点失败原因是' + e.data
											.message,
										icon: 'none'
									});
									resolve(false)
								}
								let id = e.data.data
								var value = uni.getStorageSync('account')



								// 此处是为了更换显示的离线的原始地点ID
								let storeData = uni.getStorageSync('storeData')
								console.log(storeData, '存储的数据')
								if (storeData != 'undefined' && storeData != null &&
									storeData.length > 0) {
									let index_store = storeData.findIndex(
										storeData => storeData.url ===
										'/record/getEntPlaceInfo' && storeData
										.params.entid == requestSite[i].data
										.entid)
									console.log(requestSite[i], '离线地点ENTID')

									console.log(index_store)
									if (index_store != -1) {
										let temp = JSON.parse(storeData[index_store]
											.data.data.data)
										console.log(temp, '切换地点ID')
										// 查看id是否已经存在，如果存在，则不添加,并且更换离线id,如果不存在则添加新的id
										let tempIndex = temp.findIndex(item => item
											.ID === requestSite[i].ori_id)
										if (tempIndex != -1) {
											console.log(temp)
											temp[tempIndex].ID = id

											storeData[index_store].data.data.data =
												JSON.stringify(temp)
											console.log(JSON.parse(storeData[
														index_store].data.data
													.data),
												"数据2")
										}

										uni.setStorageSync(
											'storeData',
											storeData)
									}
								}








								//获取记录本的id，然后再获取该记录本的bookid
								//获取bookid

								if (value.isckmission == 3201) {
									await common2({
										missionpeoid: value.missionpeoid,
										peoid: value.peoid,
										placeid: id,
									}, {
										'api': '/record/saveBookPlace'
									}).then(e => {
										console.log(e, 'bookid获取')
										var res5 = JSON.parse(e.data.data)

										// 更改查看数据的api，

										changeBookid(requestSite[i]
											.lx_bookid, res5.bookid)


										// 修改离线接口的id,此处的id是为了离线地点中的记录本中的材料，替换他们的bookid只有这样才能提交离线数据
										let requestFile = uni
											.getStorageSync('requestFile')
										// // 调用离线时存储的接口
										if (requestFile != 'undefined' &&
											requestFile != null &&
											requestFile
											.length > 0) {

											console.log(requestFile, '更改前')
											console.log(requestSite,
												"requestSite的数据")
											for (let j = 0; j < requestFile
												.length; j++) {
												if (requestFile[j].bookid ==
													requestSite[i].lx_bookid
												) {
													console.log(res5.bookid,
														'找到该bookid')
													requestFile[j].bookid =
														res5.bookid
													requestSite[i].realBid =
														res5.bookid

												}

											}
											console.log("更换子数据bookid成功")
											console.log(requestFile, '更改后')
											uni.setStorageSync(
												'requestFile',
												requestFile)





										}
										requestSite[i].uflag = true
										uni.setStorageSync(
											'requestSite',
											requestSite)



									})

								} else {
									await common2({
										missionpeoid: value.missionpeoid,
										peoid: value.peoid,
										placeid: id,
									}, {
										'api': '/record/saveCkBookPlace'
									}).then(e => {
										console.log(e, 'bookid获取')
										var res5 = JSON.parse(e.data.data)

										// 更改查看数据的api，

										changeBookid(requestSite[i]
											.lx_bookid, res5.bookid)
										// 修改离线接口的id,此处的id是为了离线地点中的记录本中的材料，替换他们的bookid只有这样才能提交离线数据
										let requestFile = uni
											.getStorageSync(
												'requestFile')
										// // 调用离线时存储的接口
										if (requestFile != 'undefined' &&
											requestFile != null &&
											requestFile
											.length > 0) {

											console.log(requestFile, '更改前')
											console.log(requestSite,
												"requestSite的数据")
											for (let j = 0; j < requestFile
												.length; j++) {
												if (requestFile[j].bookid ==
													requestSite[i].lx_bookid
												) {
													console.log(res5.bookid,
														'找到该bookid')
													requestFile[j].bookid =
														res5
														.bookid
													requestSite[i].realBid =
														res5.bookid
												}

											}
											console.log("更换子数据bookid成功")
											console.log(requestFile, '更改后')
											uni.setStorageSync(
												'requestFile',
												requestFile)




										}

										requestSite[i].uflag = true
										uni.setStorageSync(
											'requestSite',
											requestSite)



									})




								}



















							})


						}



					})

				}


			}

			resolve(true)
		} else {
			resolve(true)
		}
	})
}

//新增地点上传图片

function upload_picture(imgUrl) {
	const app = getApp();
	var that = this
	return new Promise(function(resolve, reject) {

		uni.uploadFile({
			url: rez_path + '/record/upload',

			filePath: imgUrl,
			name: 'file',
			formData: ({
				type: 'image'
			}),
			success: function(res) {
				var e = JSON.parse(res.data)
				if (e.status == 0) {
					console.log("提交成功")
					resolve(e.url)

				} else {
					uni.showToast({
						title: "文件上传失败，请稍后再试",
						icon: 'none'
					});
					resolve(false)
				}
			},
			fail: function() {
				app.$global.done_flag = false
				uni.showToast({
					title: "保存失败，连接服务器超时",
					icon: 'none'
				});
				resolve(false)
			}
		})

	});


}



// 同步代码块
// 此处是为了先上传图片，视频，录音等问题记录
async function donwFIle() {


	const app = getApp();



	return new Promise(async (resolve, reject) => {

		let requestFile = uni.getStorageSync('requestFile')




		console.log(requestFile, requestFile.length, '可能的数据异常')
		if (requestFile != 'undefined' && requestFile != null && requestFile.length > 0) {


			for (let i = 0; i < requestFile.length; i++) {


				console.log(requestFile, "进行了离线api文件调用")
				// 上传过的就不上传
				if (requestFile[i].uflag == true) {
					continue;
				}

				await uploadSingle(requestFile[i].path, requestFile[i].type).then(async res3 => {
					if (res3.status == 0) {


						//上传服务器成功，保存到数据表中
						await saveSingleRecordTab2(requestFile[i].time, requestFile[i].type,
							res3.url,
							requestFile[i].recordTime, requestFile[i].lx_id,
							requestFile[i]
							.bookid, requestFile[i].isckmission, requestFile[i].methodid
						).then((
							flag) => {

							requestFile[i].uflag = true
							uni.setStorageSync('requestFile', requestFile)


							// 一般文件上传要比接口的上传时间要久一些，所以标记放此处

							console.log(requestFile, '是否到了这个位置')
							return flag
							// resolve(flag)

						})

					} else {

						// app.$global.done_flag = false
						console.log(requestFile, '上传失败的文件')
						uni.showToast({
							title: '上传服务器失败，请稍后再试',
							icon: 'none'
						})
						reject(false)


					}

				})
				// console.log(requestFile)
				// requestFile.splice(j, 1)

			}

			resolve(true)
			// console.log(requestFile,'上传文件')
			// uni.setStorageSync('requestFile', requestFile)
		} else {
			resolve(true)
		}

	});
}

// 数组去重并排序
async function exArr(list) {
	
	for (let i = 0; i < list.sort().length; i++) {
	    if (list[i] == list[i + 1]) {
	        list.splice(i, 1)
	        i--
	    }
	}
	

	
	
	
	// for (var i = 0; i < list.length - 1; i++) {
	//    //控制每一轮的比较次数
	//     for (var j = 0; j < list.length - 1 - i; j++) {
	//         if (list[j] > list[j + 1]) {
	//             var temp = list[j];
	//             list[j] = list[j + 1];
	//             list[j + 1] = temp;
	//         }
	//     }
	// }
	
	
	return list
}





//存储所有操作接口

async function all_request(parameter, name) {
	let requestQueue = uni.getStorageSync('requestQueue')
	// 存储离线时调用接口的动作
	if (requestQueue != 'undefined' && requestQueue != null && requestQueue.length > 0) {

		var flag = false


		requestQueue.forEach((k, j) => {
			if (k.name.api == name.api && looseEqual(k.parameter, parameter)) {

				flag = true

			}
		})

		if (!flag) {
			let item = {}
			item.parameter = parameter
			item.name = name
			requestQueue.unshift(item)

		}


	} else {
		requestQueue = []
		let item = {}
		item.parameter = parameter
		item.name = name
		requestQueue.unshift(item)
	}
	uni.setStorageSync('requestQueue', requestQueue)
}




// 通用接口
async function common(parameter, name) {




	const app = getApp();
	if (app.$global.web_flag) {
		let result = ''
		if (name.api == 'unline') {

			// 先下载文件返回id再通过接口
			// let flag_file=false
			await upSite().then(async res => {
				console.log(res)
				// if(res){
				// flag_file = await donwFIle()
				// 
				await donwFIle().then(async res10 => {
					console.log(res10, '确认是否正确的数据')

					if (res10) {
						let requestQueue = uni.getStorageSync('requestQueue')
						console.log(requestQueue)
						// 调用离线时存储的接口
						if (requestQueue != 'undefined' && requestQueue != null &&
							requestQueue
							.length > 0) {

							for (let i = requestQueue.length - 1; i >= 0; i--) {


								if (requestQueue[i].parameter.hasOwnProperty('recordid')) {
									if (String(requestQueue[i].parameter.recordid).search(
											"lx_") != -1) {
										continue;
									}
								}




								console.log(i)
								await request({
									url: requestQueue[i].name.api,
									method: 'post',
									data: requestQueue[i].parameter
								}).then(res => {
									// console.log(res)
									// 	if (res.data.code == 0) {
									// 标记离线已经调用成功
									console.log(res)
									requestQueue.splice(i, 1)
									console.log(requestQueue)
									uni.setStorageSync('requestQueue', requestQueue)
									// }
								})
							}
						}
						return Promise.resolve("缓存成功")
					} else {
						// 让它继续上传
						app.$global.done_flag = false
						return Promise.resolve("离线失败")
					}
				})


				// }
			})
			// let flag_file = await donwFIle()
			// if (!flag_file) {
			// 	return Promise.resolve("离线失败")
			// } else {
			// 	let requestQueue = uni.getStorageSync('requestQueue')
			// 	// 调用离线时存储的接口
			// 	if (requestQueue != 'undefined' && requestQueue != null && requestQueue.length > 0) {

			// 		for (let i = requestQueue.length - 1; i >= 0; i--) {


			// 			if (requestQueue[i].parameter.hasOwnProperty('recordid')) {
			// 				if (String(requestQueue[i].parameter.recordid).search("lx_") != -1) {
			// 					// 涉及到离线新增条目的id直接跳过
			// 					continue;
			// 				}
			// 			}
			// 			console.log(i)
			// 			request({
			// 				url: requestQueue[i].name.api,
			// 				method: 'post',
			// 				data: requestQueue[i].parameter
			// 			}).then(res => {
			// 				// console.log(res)
			// 				// 	if (res.data.code == 0) {
			// 				// 标记离线已经调用成功
			// 				console.log(res)
			// 				requestQueue.splice(i, 1)
			// 				console.log(requestQueue)
			// 				uni.setStorageSync('requestQueue', requestQueue)
			// 				// }
			// 			})
			// 		}
			// 	}
			// 	return Promise.resolve("缓存成功")
			// }

		}



		result = request({
			url: name.api,
			method: 'post',
			data: parameter
		})





		return result

	} else {

		// 读取每个页面的接口存储的信息
		all_request(parameter, name)
		let data = ''
		let storeData = uni.getStorageSync('storeData')
		if (storeData != 'undefined' && storeData != null && storeData.length > 0) {
			if (storeData.find(storeData => storeData.url === name.api && looseEqual(storeData.params,
					parameter))) {
				let tem_data = storeData.find(storeData => storeData.url === name.api && looseEqual(storeData
					.params,
					parameter))
				data = tem_data.data
			} else {

				data = {
					data: {
						code: "0",
						data: '[]',
						message: "无该缓存数据"
					}

				}
			}




		}
		return Promise.resolve(data)





	}

}


async function common2(parameter, name) {


	return request({
		url: name.api,
		method: 'post',
		data: parameter
	})

}



// 提交缓存数据




function saveSingleRecordTab2(time, type, url, recordTime, lx_id, bookid, isckmission, methodid) {

	return new Promise((resolve, reject) => {
		let tempList = []
		if (type == "307901") {
			//上传录音
			tempList = [{
				"id": '',
				"time": time,
				"recordTime": recordTime,
				"formatTime": util.formatSecond(recordTime),
				"type": "307901",
				"audioStatus": false,
				"soundicon": "../images/record-icon/nosound-icon.png",
				"savePath": url,
				"remark": "",
				"maybe": 3201,
				"methodids": methodid
			}]
		} else if (type == "307902") {
			//上传图片
			tempList = [{
				"id": '',
				"time": time,
				"type": type,
				"savePath": url,
				"remark": "",
				"maybe": 3201,
				"methodids": methodid
			}]
		} else if (type == "307903") {
			//上传视频
			tempList = [{
				"id": '',
				"time": time,
				"recordTime": recordTime,
				"formatTime": util.formatSecond(recordTime),
				"type": type,
				"savePath": url,
				"remark": "",
				"maybe": 3201,
				"methodids": methodid
			}]
		}


		let contentInfo = JSON.stringify(tempList)
		if (isckmission == 3201) {



			common2({
				bookid: bookid,
				contentInfo: contentInfo
			}, {
				'api': '/record/saveRecord'
			}).then(e => {

				let res = JSON.parse(e.data.data)

				// 修改离线接口的id,此处的id是为了图片的备注和合规不合规的离线使用
				let requestQueue = uni.getStorageSync('requestQueue')
				// 调用离线时存储的接口
				if (requestQueue != 'undefined' && requestQueue != null && requestQueue.length > 0) {


					for (let i = 0; i < requestQueue.length; i++) {
						if (requestQueue[i].parameter.hasOwnProperty('recordid')) {

							if (requestQueue[i].parameter.recordid == lx_id) {
								requestQueue[i].parameter.recordid = res.recordid
							}


						}

					}
					console.log("存储数据成功")
					uni.setStorageSync('requestQueue', requestQueue)
					resolve(true)

				}









				//成功回调
				if (e.data.code == 0) {
					resolve(true)
					//保存成功
					// uni.showToast({
					// 	title: "缓存成功",
					// 	icon: 'success',
					// 	mask: true
					// });

				} else {
					//保存失败，弹出提示窗口
					resolve(false)
					// uni.showToast({
					// 	title: "缓存失败",
					// 	icon: 'none'
					// });
				}

			})







		} else {



			common2({
				bookid: this.bookid,
				contentInfo: contentInfo
			}, {
				'api': '/record/saveCkRecord'
			}).then(e => {
				let res = JSON.parse(e.data.data)


				// 修改离线接口的id
				let requestQueue = uni.getStorageSync('requestQueue')
				// 调用离线时存储的接口
				if (requestQueue != 'undefined' && requestQueue != null && requestQueue.length > 0) {


					for (let i = 0; i < requestQueue.length; i++) {
						if (requestQueue[i].parameter.hasOwnProperty('recordid')) {

							if (requestQueue[i].parameter.recordid == lx_id) {
								requestQueue[i].parameter.recordid = res.recordid
							}


						}

					}
					console.log("存储数据成功")
					uni.setStorageSync('requestQueue', requestQueue)
					resolve(true)

				}




				// this.list=tempList.concat(list)
				//成功回调
				if (e.data.code == 0) {
					resolve(true)
					//保存成功
					// uni.showToast({
					// 	title: "保存成功",
					// 	icon: 'success',
					// 	mask: true
					// });
				} else {
					//保存失败，弹出提示窗口
					resolve(false)
					// uni.showToast({
					// 	title: "保存失败",
					// 	icon: 'none'
					// });
				}
			})



		}
	})


}








// 上传文件


function uploadSingle(path, type) {
	const app = getApp();


	let requestFile = uni.getStorageSync('requestFile')
	console.log(requestFile, '剩余多少')
	let unloadn = 0
	if (requestFile != 'undefined' && requestFile != null && requestFile.length > 0) {
		for (let i = 0; i < requestFile.length; i++) {
			if (requestFile[i].uflag == false) {
				unloadn++;
			}
		}
	}

	app.$global.unloadn = unloadn


	let p = new Promise(function(resolve, reject) {
		let uploadTask = uni.uploadFile({
			url: rez_path + '/record/upload',
			// header: {
			//   "content-type": "multipart/form-data"
			// },
			filePath: path,
			name: 'file',
			formData: ({
				type: type
			}),
			success: function(res) {
				console.log(res);

				var e = JSON.parse(res.data)

				resolve(e);
			},
			fail: function() {
				app.$global.done_flag = false
				reject(false)
				uni.showToast({
					title: "保存失败，连接服务器超时",
					icon: 'none'
				});
			}
		})

		uploadTask.onProgressUpdate((res) => {
			app.$global.progress = res.progress
			// 显示剩余多少文件未上传的
			// console.log(res.progress, '当前进度')

		});
	});
	return p;
}






// 找相同formdata数据
//判断两个对象是否相同（包含绝对相等和他们是否有相同的形状）
function looseEqual(a, b) {
	if (a === b) { //如果是绝对相等就直接返回true
		return true;
	}
	//如果不是绝对相等就哦按的他们是否有相同的形状
	var isObjectA = isObject(a);
	var isObjectB = isObject(b);
	if (isObjectA && isObjectB) { //两个均是对象
		try {
			var isArrayA = Array.isArray(a);
			var isArrayB = Array.isArray(b);
			if (isArrayA && isArrayB) { //如果都是数组
				if (a.length === b.length) { //如果长度相等
					return a.every(function(e, i) { //用every和递归来比对a数组和b数组的每个元素，并返回
						return looseEqual(e, b[i])
					})
				}
				//长度都不等直接返回false
				return false;
			} else if (a instanceof Date && b instanceof Date) { //如果是Date 则直接getTime 比较
				return a.getTime() === b.getTime()
			} else if (!isArrayA && !isArrayB) { //对象的比较
				//拿到两个对象的key
				var keysA = Object.keys(a);
				var keysB = Object.keys(b);
				if (keysA.length === keysB.length) { //如果keys相等
					return keysA.every(function(key) { //用every和递归来比对a对象和b对象的每个元素值，并返回
						return looseEqual(a[key], b[key]);
					})
				}
				//长度都不等直接返回false
				return false;
			} else {
				return false
			}
		} catch (e) {
			return false
		}
	} else if (!isObjectA && !isObjectB) { //如果都不是对象则按String来处理
		return String(a) === String(b)
	} else {
		return false
	}
}

function isObject(obj) {
	return obj !== null && typeof obj === 'object'
}


module.exports = {
	common: common,
	getEntRegInfo: getEntRegInfo,
	getFacInfo: getFacInfo,
	getPlant: getPlant,
	previewImage: previewImage
}

// 图片预览
function previewImage(url) {
	let tem = []
	tem.push(url)
	uni.previewImage({
		current: 1,
		urls: tem
	})
}

/* 
 *	获取企业信息
 */
function getEntRegInfo(parameter) {

	return request({
		url: api.getEntRegInfo,
		method: 'post',
		params: parameter
	})
}









/* 
 *	获取厂区信息
 */
function getFacInfo(parameter) {

	return request({
		url: api.getFacInfo,
		method: 'post',
		params: parameter
	})
}




/* 
 *	获取车间详细信息
 */
function getPlant(parameter) {

	return request({
		url: api.getPlant,
		method: 'post',
		params: parameter
	})
}